<template>
    <div>
        <div class="directory-container">
            <v-jstree
                class="list"
                
                @item-click="directoryClick"
                v-bind="treeOption"
                ref="directoryTree"
            ></v-jstree>
        </div>
        <div class="menu-backdrop" style="position: fixed; top: 0; left: 0; z-index: 1003; width: 100%; height: 100%;" v-if="menuObj" @click="hideMenu" @contextmenu.prevent="hideMenu"></div>
        <div class="dropdown-menu directory-menu" :style="directoryMenuStyle" v-if="menuObj">
            <a class="dropdown-item" href="#" @click.prevent="$emit('rename', menuObj);hideMenu();" v-if="active && active != '/'"><i class="material-icons text-success align-middle">edit</i>重命名</a>
            <a class="dropdown-item" href="#" @click.prevent="$emit('create', menuObj);hideMenu();"><i class="material-icons text-success align-middle">add</i>添加子目录</a>
            <a class="dropdown-item" href="#" @click.prevent="$emit('delete', menuObj);hideMenu();" v-if="active && active != '/'"><i class="material-icons text-danger align-middle">remove</i>移除该目录</a>
        </div>
    </div>
        
    
</template>

<script type="text/javascript">
import Scrollbar from 'smooth-scrollbar'
import vJstree from 'vue-jstree'
import $ from 'jquery'
import _ from 'lodash'

function makeNode(map, _id, parent, closed) {
  if (closed[_id]) {
    return null;
  }
  closed[_id] = true;
  var obj = map[_id];
  if (obj) {
    var c_p = parent ? parent + obj.name + '/' : '/';
    var dnode = {
      text: obj.name,
      value: _id,
      opened: true,
      selected: false,
      path: c_p,
      ref: obj,
      children: obj.next.map(function(_id) {
        return makeNode(map, _id, c_p, Object.assign({}, closed));
      }).filter(x => x)
    };
    return dnode;
  } else {
    console.log('ircorrect _id, not found in map:', _id);
    return null;
  }
}

export default {
    name: 'directory-list',
    components: {
        vJstree
    },
    props: {
        option: {
            type: Object,
            default() {
                return {}
            }
        },
        data: {
            type: Object,
            required: true
        },
        root: {
            type: String,
            required: true
        },
        active: {
            type: String,
            default: "/"
        },
    },
    data() {
        var vm = this;
        return {
            menuObj: null,
            directoryItemEvent: {
                contextmenu: function (vn, item, e) {
                  var {clientX, clientY} = e;
                  vm.directoryClick(vn, item, e);
                  vm.menuObj = {
                    vn: vn,
                    item: item,
                    event: e,
                    clientX,
                    clientY,
                    directory: item.ref
                  };
                  e.preventDefault();
                }
            }
        }
    },
    computed: {
        treeOption() {
            return $.extend({
                data: this.directory,
                'item-events': this.directoryItemEvent
            }, this.option);
        },
        directoryMenuStyle() {
          return {
            display: this.menuObj ? 'block' : 'none',
            position: 'fixed',
            zIndex: 1003,
            top: this.menuObj ? this.menuObj.clientY + 'px' : 0,
            left: this.menuObj ? this.menuObj.clientX + 'px' : 0
          }
        },
        directory() {
            var db = this.data;
            var RootNode = makeNode(db, this.root, null, {});
            return [RootNode];
        }
    },
    methods: {
        hideMenu() {
            this.menuObj = null;
        },
        directoryClick(vn, item, e) {
            if (e) {
                this.$emit('item-click', item, e);
            }
        },
        initialActive: function() {
            var vm = this,
                di = this.getDirectoryVm(this.active);
            if (!di) {
                vm.$emit('path-not-found');
            } else {
                di.handleItemClick(null);
                vm.$emit('item-init', di, di.model);
            }
        },
        getDirectoryObj(path) {
            var vm = this,
                di = this.getDirectoryItem(path);
            if (di) {
                return di.ref;
            } else {
                return null;
            }
        },
        getDirectoryItem(path) {
            var vm = this,
                di = this.getDirectoryVm(path);
            if (di) {
                return di.model;
            } else {
                return null;
            }
        },
        getDirectoryVm(path) {
            var vTree = this.$refs.directoryTree,
                vm = this;

            var arr = path.split('/').filter(x => x);

            if (path.slice(0, 1) == '/' || !arr.length) {
                arr.unshift(vm.data[vm.root].name);
            }

            var cn = vTree;
            while (arr.length) {
                var curName = arr.shift(), finded = false;
                cn.$children.forEach(x => {
                    if (finded) {
                        return false;
                    }
                    if (x.model && x.model.ref.name == curName) {
                        finded = true;
                        cn = x;
                    }
                });
                if (!finded) {
                    return null;
                }
            }
            return cn;
        }
    },
    watch: {
        active() {
            this.initialActive();
        },
        // data: {
        //     deep: true,
        //     handler() {
        //         this.$nextTick(() => {
        //             this.initialActive();
        //         })
        //     }
        // }
    },
    created() {
        this.$nextTick(() => {
            console.log('init active');
            this.initialActive();
        })
    },
    destroyed() {
        console.log('destoryed');
        Scrollbar.destroy(this.$el.querySelector('.directory-container'));
    },
    mounted() {
        Scrollbar.init(this.$el.querySelector('.directory-container'));
    }
}
</script>

<style type="text/css">
.directory-container {
    width: 100%;
    text-align: left;
}
.directory-menu {

}

.directory-menu i {
  font-size: 12px;
  margin-right: 5px;
}

.directory-container .list {
    display: inline-block;
}
</style>